package com.coder.algorithm.offer_2;

/**
 * 和为 s 的连续正数序列
 *
 * @author yuhushuan
 * @date 2020/7/1 11:45
 */
public class _57_2_ContinuousSequenceWithSum {

    private static void findNumbersWithSum(int sum) {
        if (sum <= 2) {
            System.out.println("the sum is too small");
            return;
        }
        int start = 1;
        int end = 2;
        int curSum = start + end;
        while (2 * start < sum) {
            if (curSum == sum) {
                StringBuilder array = new StringBuilder();
                for (int i = start; i < end; ++i) {
                    array.append(i).append(", ");
                }
                array.append(end);
                System.out.println(array.toString());
                curSum -= (start++);
            } else if (curSum < sum) {
                curSum += (++end);
            } else {
                curSum -= (start++);
            }
        }
    }

    public static void main(String[] args) {
        // 功能测试
        // 存在和为 s 的连续序列
        print(9);
        print(15);
        print(100);
        // 不存在
        print(0);
        print(4);

        // 边界值测试
        print(3);
    }

    private static void print(int sum) {
        System.out.println("和为 " + sum + " 的连续正数序列：");
        findNumbersWithSum(sum);
    }

}
